var express = require('express');
var sql = require('../sql/index');
var Admin = require('../sql/col/Admin');
var uuid = require('node-uuid');
var md5 = require('md5');
var jwt = require('jsonwebtoken');
var router = express.Router();

router.get('/list', (req, res, next) => {
  sql.find(Admin, {}, { _id: 0, password:0 }).then(data => {
    res.send({
      code: '200',
      message: 'reactAdmin-获取所有的管理员的用户信息',
      data
    })
  })
})

router.post('/add', (req, res, next) => {
  let { adminname, password, role } = req.body
  // 判断当前账户名是否存在
  sql.find(Admin, { adminname }, { _id:0 }).then(data => {
    if (data.length > 0) {
      res.send({
        code: '10006',
        message: '该账户名已经存在'
      })
    } else {
      password = md5(password)
      const adminid = 'admin_' + uuid.v1()
      sql.insert(Admin, { adminid, adminname, password, role }).then(() => {
        res.send({
          code: '200',
          message: 'reactAdmin-添加管理员',
          data: [{ adminid, adminname, role }]
        })
      })
    }
  })
})

router.post('/delete', (req, res, next) => {
  const { adminid } = req.body
  sql.delete(Admin, { adminid }).then(() => {
    res.send({
      code: '200',
      message: 'reactAdmin-删除指定管理员信息',
    })
  })
})

router.post('getAdmin', (req, res, next) => {
  const { adminid } = req.body
  sql.find(Admin, { adminid }, { _id:0, password:0,}).then(data => {
    res.send({
      code: 200,
      message: 'reactAdmin-获取指定管理员的信息',
      data
    })
  })
})

router.post('/update', (req, res, next) => {
  const { adminname, role } = req.body
  sql.update(Admin, { adminname }, { $set: { role }}).then(() => {
    res.send({
      code: '200',
      message: 'reactAdmin-更新指定管理员角色信息'
    })
  })
})

router.post('/login', (req, res, next) => {
  let { adminname, password } = req.body
  password = md5(password)
  sql.find(Admin, { adminname, password }, { id:0, password: 0}).then(data => {
    if (data.length === 0) {
      res.send({
        code: '10008',
        message: '账号和密码不匹配'
      })
    } else {
      const token = jwt.sign({ adminname, password }, 'lmx-react', {
        expiresIn: 60 * 60 // 单位为秒数
      })
      res.send({
        code: '200',
        message: '登录成功',
        data: {
          adminid: data[0].adminid,
          adminname,
          role: data[0].role,
          token
        }
      })
    }
  })
})

module.exports = router;